import Taro from "@tarojs/taro";
import { create } from "zustand";

type UserStore = {
  token: string;
  setToken: (val: string) => void;

  username: string;
  setUsername: (val: string) => void;

  avatar: string;
  setAvatar: (val: string) => void;

  gender: boolean;
  setGender: (val: boolean) => void;

  role: string;
  setRole: (val: string) => void;

  balance: number;
  setBalance: (val: number) => void;

  addressList: AddressList[];
  setAddressList: (val: AddressList[]) => void;

  logout: () => void;
}

export const useUserStore = create<UserStore>((set) => {
  const token = Taro.getStorageSync("token") || "";
  const username = Taro.getStorageSync("username") || "";
  const avatar = Taro.getStorageSync("avatar") || "";
  const gender = Taro.getStorageSync("gender") || "";
  const role = Taro.getStorageSync("role") || "";
  const balance = Taro.getStorageSync("balance") || "";
  const addressList = Taro.getStorageSync("addressList") || "";
  return {
    token,
    setToken: (val) => {
      Taro.setStorageSync("token", val);
      set({ token: val });
    },

    username,
    setUsername: (val) => {
      Taro.setStorageSync("username", val);
      set({ username: val });
    },

    avatar,
    setAvatar: (val) => {
      Taro.setStorageSync("avatar", val);
      set({ avatar: val });
    },

    gender,
    setGender: (val) => {
      Taro.setStorageSync("gender", val);
      set({ gender: val });
    },

    role,
    setRole: (val) => {
      Taro.setStorageSync("role", val);
      set({ role: val });
    },

    balance,
    setBalance: (val) => {
      Taro.setStorageSync("balance", val);
      set({balance: val});
    },

    addressList,
    setAddressList: (val) => {
      Taro.setStorageSync("addressList", val);
      set({ addressList: val });
    },

    logout: () => {
      Taro.clearStorageSync();

      set({
        token: "",
        username: "",
        avatar: "",
        gender: false,
        role: "",
        addressList: []
      });

      Taro.switchTab({ url: "/pages/index/index" })
    }
  }
});

